from flask import Flask
from dotenv import load_dotenv

from config import Config
from router.router import Router
from injector import Injector
from pkg import CustomException, json, Response, HttpCode
from extensions.extensions import (db, init_app, migrate)
from app.module import ExtensionModule


def create_app():
    load_dotenv()
    app = Flask(__name__)
    config_instance = Config()
    app.config.update(config_instance.__dict__)
    init_app(app)
    migrate.init_app(app, db, directory="migrations")
    injector = Injector([ExtensionModule])

    # with app.app_context():
    #     db.create_all()

    # injector = Injector()
    router = injector.get(Router)
    router.register_router(app)

    app.register_error_handler(Exception, error_handler)

    return app, injector


def error_handler(err: Exception):
    if isinstance(err, CustomException):
        return json(Response(
            code=err.code,
            message=err.message,
            data=err.data if err.data is not None else {},
        ))
    if app.debug:
        return err

    return json(Response(code=HttpCode.FAILED, message=str(err), data={}))


app, injector = create_app()
if __name__ == '__main__':
    app.run(debug=True)
